<?php

namespace app\modules\controllers;

use app\modules\models\Menu;
use Yii;
use yii\data\Pagination;



class MenuController extends CommonController
{

    protected $mustlogin = ['list','add','mod','del'];

    public function actionList()
    {
        $this->layout = "layout1";
        $model = new Menu();
        $menus = $model->getTreeList();
        return $this->render("list", ['menus' => $menus]);
    }

    public function actionAdd()
    {
        $this->layout = "layout1";
        $model = new Menu();
        $list = $model->getOptions();
        if (Yii::$app->request->isPost) {
            $post = Yii::$app->request->post();
            if ($model->add($post)) {
                Yii::$app->session->setFlash("info", "添加成功");
            }
        }
        return $this->render('add',['list'=>$list,'model'=>$model]);
    }


    public function actionMod()
    {
        $this->layout = "layout1";
        $cateid = Yii::$app->request->get("cateid");
        $model = Menu::find()->where('cateid = :id', [':id' => $cateid])->one();
        if (Yii::$app->request->isPost) {
            $post = Yii::$app->request->post();
            $model->updateTime=time();
            if ($model->load($post) && $model->save()) {
                Yii::$app->session->setFlash('info', '修改成功');
            }
        }
        $list = $model->getOptions();
        return $this->render('add', ['model' => $model, 'list' => $list]);
    }

    public function actionDel()
    {
        try {
            $cateid = Yii::$app->request->get('cateid');
            if (empty($cateid)) {
                throw new \Exception('参数错误');
            }
            $data = Menu::find()->where('parentid = :pid', [":pid" => $cateid])->one();
            if ($data) {
                throw new \Exception('该菜单下有子菜单，不允许删除');
            }
            if (!Menu::deleteAll('cateid = :id', [":id" => $cateid])) {
                throw new \Exception('删除失败');
            }
        } catch(\Exception $e) {
            Yii::$app->session->setFlash('info', $e->getMessage());
        }
        return $this->redirect(['menu/list']);
    }




}